import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Drawer, Form, FormProps, Input, Space } from 'antd';
import dayjs from 'dayjs';

import { store } from '@/store';

import {
  safeEmergencyExercisesAdd,
  safeEmergencyExercisesUpdate
} from '@/services/bizApi/anquanyingjiguanliyanlianjilubiaojiekou';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        exerciseTime: values?.exerciseTime
          ? dayjs(values?.exerciseTime).format('YYYY-MM-DD')
          : undefined
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit'
        ? safeEmergencyExercisesUpdate(query)
        : safeEmergencyExercisesAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData,
              exerciseTime: arg.rowData?.exerciseTime ? dayjs(arg.rowData?.exerciseTime) : undefined
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增',
          edit: '编辑',
          detail: '详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="演练科目"
          name="exerciseSubject"
          rules={[
            {
              required: true,
              message: '请输入演练科目'
            }
          ]}
        >
          <Input placeholder="请输入演练科目" />
        </Form.Item>
        <Form.Item
          label="演练时间"
          name="exerciseTime"
          rules={[
            {
              required: true,
              message: '请选择演练时间'
            }
          ]}
        >
          <DatePicker placeholder="请选择演练时间" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="演练地点"
          name="exerciseLocation"
          rules={[
            {
              required: true,
              message: '请输入演练地点'
            }
          ]}
        >
          <Input placeholder="请输入演练地点" />
        </Form.Item>
        <Form.Item
          label="演练方式"
          name="exerciseMethod"
          rules={[
            {
              required: true,
              message: '请输入演练方式'
            }
          ]}
        >
          <Input placeholder="请输入演练方式" />
        </Form.Item>
        <Form.Item
          label="演练内容"
          name="exerciseContent"
          rules={[
            {
              required: true,
              message: '请输入演练内容'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入演练内容" />
        </Form.Item>
        <Form.Item
          label="演练过程描述"
          name="processDescription"
          rules={[
            {
              required: false,
              message: '请输入演练过程描述'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入演练过程描述" />
        </Form.Item>
        <Form.Item
          label="演练小结"
          name="summary"
          rules={[
            {
              required: false,
              message: '请输入演练小结'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入演练小结" />
        </Form.Item>
        <Form.Item
          label="演练效果评价"
          name="effectEvaluation"
          rules={[
            {
              required: false,
              message: '请输入演练效果评价'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入演练效果评价" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
